package tbmanager;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;

import student.Student;
import util.HibernateUtil;

/**
 * Servlet implementation class Manager
 */
@WebServlet("/Manager")
public class Manager extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Manager() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Session session=HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		String hql="from Student";
		Query query=session.createQuery(hql);
		List<Student> stulist=query.list();
		String json="{\"students\":[";
			for (int i=0;i<stulist.size();i++){
				json+="{\"sid\":\""+stulist.get(i).getSid()+"\"";
				json+=",\"name\":\""+stulist.get(i).getName()+"\"";
				json+=",\"gender\":\""+stulist.get(i).getGender()+"\"";
				json+=",\"did\":\""+stulist.get(i).getDepartment().getDid()+"\"";
				json+=",\"dname\":\""+stulist.get(i).getDepartment().getDname()+"\"}";
				if(i<stulist.size()-1) json+=",";
				else json+="]}";
			}
			System.out.println(json);
			response.setCharacterEncoding("utf-8");
			PrintWriter out=response.getWriter();
			out.write(json);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
